<template>
  <div class="common-container">
    <head-title is-detail :title="title" :link-path="linkPath" />

    <div class="header-wrap center-box">
      <div class="common-search ym-box">
        <search-form :form="searchForm" :center-options="state.centerOptions" @search="search" />
      </div>
    </div>

    <div class="table-wrap ym-box center-box">
      <div :style="{ height: tableHeight + 'px' }">
        <filter-wrap
          v-model:status-code="searchForm.issuesStatus"
          :status-data="issuesStatus"
          @search="search(false, false)"
        />
        <div class="table-body">
          <div v-loading="state.tableLoading" class="table-body__left">
            <div v-if="issuesList.length > 0" class="issues-list">
              <div
                v-for="issues in issuesList"
                :key="issues.vid"
                class="issues-item"
                :class="{ 'is-active': currentIssues.vid === issues.vid }"
                @click="selectIssue(issues)"
              >
                <div class="issues-title">
                  <span>{{ issues.name }}</span>
                </div>
                <el-row class="issues-info">
                  <el-col :span="12">
                    <div class="issues-info__label">受试者</div>
                    <div class="issues-info__content">{{ currentIssues.subject.sic }}</div>
                  </el-col>
                  <el-col :span="12">
                    <div class="issues-info__label">访视时间</div>
                    <div class="issues-info__content">{{ currentIssues.visitTime }}</div>
                  </el-col>
                </el-row>
                <el-row class="issues-info">
                  <el-col>
                    <div class="issues-info__label">研究中心</div>
                    <div class="issues-info__content">{{ currentIssues.centre }}</div>
                  </el-col>
                </el-row>
              </div>
            </div>
            <empty v-else />
          </div>
          <div v-loading="state.tableLoading" class="table-body__main">
            <div v-if="currentIssues.vid">
              <div class="info-top">
                <div class="issues-baseinfo">
                  <div class="issues-title">{{ currentIssues.name }}</div>
                  <!-- <div class="issues-status">{{ currentIssues.statusValue }}</div>
                  <div class="issues-level">一般</div>-->
                </div>
                <div class="btn-wrap">
                  <el-button type="primary" @click="submitIssues">提交</el-button>
                </div>
              </div>

              <div v-if="currentIssues.issues" class="main-content">
                <div class="main-left">
                  <center :info="currentIssues" />
                </div>
                <div class="main-right">
                  <right :info="currentIssues" />
                </div>
              </div>
              <div v-else class="main-content">
                <issues-form v-if="currentIssues.vid" ref="issuesForm" />
              </div>
            </div>
            <empty v-else />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, reactive, ref, toRefs, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'

import FilterWrap from '../components/FilterWrap.vue'
import SearchForm from '../components/SearchForm.vue'
import Empty from '@/components/EmptyBlock/index.vue'
import HeadTitle from '@/components/HeaderTitle/index.vue'
import Center from './Center.vue'
import IssuesForm from './IssuesForm.vue'
import Right from './Right.vue'

import { getOrgClsListByPid, orgType } from '@/api/common'
import IssuesApi from '@/api/issues'
import VisitApi from '@/api/visit'

import { useTable } from '@/utils/common/useTable'

import CommonState from './issuesState'
import IBaseObj from '#/index'

const { getDictData } = CommonState

const route = useRoute()
const router = useRouter()
const { pid, pname, isuId }: IBaseObj = route.query
const linkPath = `/project/issues?pid=${pid}&pname=${pname}`
const { tableHeight } = useTable()

defineProps({
  title: {
    type: String,
    default: '质疑处理',
  },
})

const state: IBaseObj = reactive({
  issuesList: [],
  issuesStatus: [],
  currentIssues: {},
  tableLoading: true,
})
const { currentIssues, issuesList, issuesStatus } = toRefs(state)

/* search srart */

watch(
  () => state.currentIssues.vid,
  (val) => {
    if (val) {
      router.push(`/project/issues/detail?pid=${pid}&pname=${pname}&isuId=${val}`)
    } else {
      state.visitList = []
      router.push(`/project/issues/detail?pid=${pid}&pname=${pname}`)
    }
  }
)

const searchForm = reactive({
  issues: '',
  issuesStatus: 0,
})

// 获取状态
const getStatusData = async () => {
  const ret = await VisitApi.getIssuesStatus({
    pid,
    issues: 1,
  })
  state.issuesStatus = ret || []
  initSearch()
}

// 初始将选中的数据变为第一条数据
const formatIssues = () => {
  const index = state.issuesList.findIndex((v: IBaseObj) => v.vid === isuId * 1)
  const item = state.issuesList[index]
  state.issuesList.splice(index, 1)
  item && state.issuesList.unshift(item)
}

// 选中访视的查询
/**
 * isInit 初始
 * isShoseItem 是否是点击访视
 */
const search = async (isInit = false, isShoseItem = false) => {
  state.tableLoading = true
  try {
    const ret = await VisitApi.getIssuesList({ ...searchForm, pid, issues: 1 })
    state.issuesList = ret
    if (isInit) {
      formatIssues()
    }

    if (state.issuesList?.length > 0) {
      if (isInit || !isShoseItem) {
        state.currentIssues = state.issuesList[0]
      }
    } else {
      state.currentIssues = {}
    }
  } finally {
    state.tableLoading = false
  }
}

// 非选中访视查询
const initSearch = async () => {
  search(true)
}

// 点击切换访视
const selectIssue = (issues: IBaseObj) => {
  state.currentIssues = issues
  search(false, true)
}

// 获取研究中心
const getCenterOptions = async () => {
  const ret = await getOrgClsListByPid(pid, orgType.yjdw)
  state.centerOptions = ret.data
}

// 初始化操作
const init = () => {
  getCenterOptions()
  getStatusData()
  getDictData()
}
init()

/* search end */

/* 提交issues  start */

const issuesForm = ref()
const submitIssues = async () => {
  issuesForm.value.$refs.formRef.validate(async (valid: boolean) => {
    if (valid) {
      const ret = await IssuesApi.addNewIssues({
        ...issuesForm.value.form,
        pid: state.currentIssues.pid,
        vid: state.currentIssues.vid,
        sic: state.currentIssues.subject.sic,
        centreId: state.currentIssues.centreId,
        subId: state.currentIssues.subId,
      })
      if (ret) {
        ElMessage({ message: '提交成功！', type: 'success' })
        initSearch()
      }
    }
  })
}

/* 提交issues  end */
</script>

<style lang="scss" scoped>
.table {
  &-body {
    display: flex;
    height: calc(100% - 41px);

    & > div {
      height: 100%;
      overflow: auto;
      @include scroll-bar;
    }

    &__left {
      width: 300px;
      padding: 0 20px;
      border-right: 1px solid var(--table-border);
    }

    &__main {
      display: flex;
      flex-direction: column;
      flex: 1;

      .info-top {
        display: flex;
        padding: 10px;
        border-bottom: 1px solid var(--table-border);
        align-items: center;
        justify-content: space-between;
      }

      .issues-baseinfo {
        display: flex;
        align-items: center;

        .issues-title {
          margin-bottom: 0;
        }
      }

      .issues-status {
        padding: 4px 8px;
        margin-left: 10px;
        border: 1px solid var(--color-success);
        border-radius: 4px;
      }

      .issues-level {
        padding: 4px 8px;
        margin-left: 10px;
        border: 1px solid var(--color-success);
        border-radius: 4px;
      }

      .main {
        &-content {
          display: flex;
          flex: 1;
        }

        &-left {
          flex: 1;
          padding: 20px;
        }

        &-right {
          width: 300px;
          padding: 20px 20px 0 20px;
          border-left: 1px solid var(--table-border);
        }
      }
    }
  }
}

.issues {
  height: 40px;

  &-list {
    padding-top: 20px;
  }

  &-item {
    // display: flex;
    // height: 40px;
    // padding-left: 16px;
    padding: 16px;
    cursor: pointer;
    // align-items: center;

    // font-size: 16px;
    // font-weight: 600;
    background: var(--background-color-1);
    border-radius: 6px;

    & + & {
      margin-top: 10px;
    }

    &:hover {
      background: var(--card-hover-background);
    }

    &.is-active {
      background: var(--card-active-background);
    }

    .shape {
      width: 14px;
      height: 14px;
      margin-right: 10px;
      background: var(--color-primary);
    }

    .circle {
      border-radius: 50%;
    }

    .rect {
      position: relative;
      font-size: 14px;
      color: white;

      &::after {
        position: absolute;
        top: 50%;
        left: 50%;
        content: '√';
        transform: translate(-50%, -50%);
      }
    }
  }

  &-title {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    line-height: 1.5;
  }

  &-info {
    padding: 5px 0;

    &__label {
      font-size: 12px;
    }

    &__content {
      font-size: 16px;
      font-weight: 600;
    }
  }
}
</style>
